// 引入service层
const {
  insertOrder,
  gainOrderList,
  updateOrderStatus,
} = require("../service/order.service");

// 创建订单控制器
class OrderController {
  // 创建订单
  async createOrder(ctx, next) {
    const {
      userId,
      contactId,
      totalPrice,
      goodsList,
      orderStatus = "0",
    } = ctx.request.body;
    // 获取用户id、收件地址id、总价、商品列表、订单状态为预设值
    // // 操作数据库
    try {
      const result = await insertOrder({
        userId,
        contactId,
        totalPrice,
        goodsList,
        orderStatus,
      });

      if (result) {
        ctx.response.body = {
          code: 200,
          message: "创建成功",
          data: result.dataValues,
        };
        next();
      }
    } catch (error) {
      console.log(error);
    }
  }

  // 获取订单列表
  async getOrderList(ctx, next) {
    // 获取用户id
    const { userId, status = "0" } = ctx.query;
    console.log(userId, status);
    // 获取订单列表
    try {
      const result = await gainOrderList({ userId, status });
      if (result) {
        ctx.response.body = {
          code: 200,
          message: "查询成功",
          data: result,
        };
        next();
      }
    } catch (error) {
      console.log(error);
    }
  }
  // 确认收货
  async confirmOrder(ctx, next) {
    const { orderId } = ctx.request.body;
    try {
      const result = await updateOrderStatus({ orderId });
      if (result) {
        ctx.response.body = {
          code: 200,
          message: "确认收货成功",
          data: result,
        };
        next();
      }
    } catch (error) {
      console.log(error);
    }
  }
}

// 导出实例
module.exports = new OrderController();
